import { Backdrop, Box, CircularProgress, Typography } from "@mui/material";
import React, { useEffect, useState } from "react";
import { useLocation, useNavigate, useParams } from "react-router-dom";
import { toast } from "react-toastify";
import { filterImage } from "../App";
import PostForm from "../components/PostForm";
import { editPost, getFriendStyles } from "../services/api";

export default function EditPost() {
  const [isLoading, setIsLoading] = useState(false);
  const [friendStyles, setFriendStyles] = useState([]);
  const navigate = useNavigate();
  const { id } = useParams();
  const location = useLocation();
  const post = location.state?.post;

  useEffect(() => {
    const fetchFriendStyles = async () => {
      try {
        const response = await getFriendStyles();
        setFriendStyles(response.result);
      } catch (error) {
        console.error("Failed to fetch friend styles:", error);
        toast.error("Failed to fetch friend styles. Please try again.");
      }
    };

    fetchFriendStyles();
  }, []);

  // Redirect to dashboard if no post data is available
  if (!post) {
    navigate("/");
    return null;
  }

  const handleSubmit = async (formData) => {
    try {
      setIsLoading(true);
      await editPost(id, formData);
      toast.success("Post updated successfully");
      // Only navigate after successful save
      navigate("/");
    } catch (error) {
      toast.error(error.message || "Failed to update post");
      console.error("Error updating post:", error);
      setIsLoading(false); // Only reset loading on error
    }
  };

  return (
    <Box>
      <Typography variant="h4" gutterBottom>
        Edit Post
      </Typography>
      <PostForm
        initialData={{
          ...post,
          imageUrls: (post.imageUrls || []).map((img) => filterImage(img, 800)),
          customProfileName: post.customProfileName || "",
          customProfileUrl: post.customProfileUrl || "",
        }}
        onSubmit={handleSubmit}
        isLoading={isLoading}
      />
      <Backdrop
        sx={{
          color: "#fff",
          zIndex: (theme) => theme.zIndex.drawer + 1,
          display: "flex",
          flexDirection: "column",
          gap: 2,
        }}
        open={isLoading}
      >
        <CircularProgress color="inherit" />
        <Typography>Saving your changes...</Typography>
      </Backdrop>
    </Box>
  );
}
